package com.example.xd.default_call.fragment

import android.os.Handler
import android.os.Message
import android.telecom.Call
import android.view.View
import com.example.xd.default_call.R
import com.example.xd.default_call.TimeFormatUtil
import com.example.xd.default_call.eventbus_msg.CallOutStartMsg
import kotlinx.android.synthetic.main.fragment_call_out.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @auther XuDan on 2020/8/13.
 */
class Call_Out_Fragment : BaseFragment(), View.OnClickListener {
    var time: Long = 0
    var mHandler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 1) {
                time++
                call_out_time_tv.setText("通话时长：" + TimeFormatUtil.instance.stringForTime(time))
                val obtain = Message.obtain()
                obtain.what = 1
                sendMessageDelayed(obtain, 1000)
            }
        }
    }

    override fun registerMethod() {
        EventBus.getDefault().register(this)
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_call_out
    }

    override fun initViews(view: View) {
        call_out_cut_img.setOnClickListener(this)
    }

    override fun unRegisterMethod() {
        EventBus.getDefault().unregister(this)
    }

    lateinit var call: Call

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun callStart(msg: CallOutStartMsg) {
        call = msg.call
        val phone = call.details.handle.toString().substring(4).replace("%20", "")
        call_out_phone_tv.setText(phone)
        call_out_time_tv.setText("")
        call.registerCallback(MyCallBack())
    }

    override fun onClick(v: View?) {
        when (v) {
            call_out_cut_img -> {
                call.disconnect()
                call_out_time_tv.setText("通话结束")
                mHandler.removeCallbacksAndMessages(null)
                mActivity.finish()
            }
        }
    }

    inner class MyCallBack : Call.Callback() {
        override fun onStateChanged(call: Call, state: Int) {
            super.onStateChanged(call, state)
            when (state) {
                Call.STATE_ACTIVE -> {
                    val msg = Message.obtain()
                    msg.what = 1
                    mHandler.sendMessage(msg)
                }
                Call.STATE_DISCONNECTED -> {
                    call_out_time_tv.setText("通话结束")
                    mHandler.removeCallbacksAndMessages(null)
                    mActivity.finish()
                }
            }
        }

    }
}